<template>
  <div class="main">
    <!-- <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox> -->
    <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox>
    <!-- <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
    <el-tree class="tree-border" :data="menuOptions" show-checkbox ref="menuRef" :node-key="nodeKey" :check-strictly="!menuCheckStrictly" empty-text="加载中，请稍候" :props="{ label: 'name' }" @check="handleCheckChange" :default-expand-all="props.expandAll==1"></el-tree>
  </div>
</template>

<script setup lang="ts">
import { nextTick, onMounted } from "vue";
let props = defineProps(["modelValue", "defaultChecked", "expandAll"]);
const emit = defineEmits(["update:modelValue"]);
const { proxy } = getCurrentInstance();
const menuExpand = ref(false);
const menuNodeAll = ref(false);
let menuCheckStrictly = ref(false);
let menuOptions = ref([]);
let expandAll = ref(true); //默认全部展开
let nodeKey = ref("id");
let addIds = [];

onMounted(() => {
  getInfo();
});

let getInfo = async () => {
  let array = await proxy.$apis.menuList({});
  array.forEach((element) => {
    addIds.push(element.id);
  });
  let items = proxy.$utils.transformArray(array, "id", "parentId");
  menuOptions.value = sortItems(items, "asc", "sort");
};
//字段排序
function sortItems(items: Item[], sortOrder: "asc" | "desc", field): Item[] {
  return items
    .sort((a, b) => {
      if (sortOrder === "asc") {
        return a[field] - b[field];
      } else {
        return b[field] - a[field];
      }
    })
    .map((item) => {
      if (item.children) {
        item.children = sortItems(item.children, sortOrder, field);
      }
      return item;
    });
}
/** 树权限（展开/折叠）*/
function handleCheckedTreeExpand(value, type) {
  let treeList = menuOptions.value;
  for (let i = 0; i < treeList.length; i++) {
    proxy.$refs.menuRef.store.nodesMap[treeList[i][nodeKey.value]].expanded =
      value;
  }
}
/** 树权限（全选/全不选） */
function handleCheckedTreeNodeAll(value, type) {
  proxy.$refs.menuRef.setCheckedNodes(value ? menuOptions.value : []);
  emit("update:modelValue", value ? addIds : []);
}
/** 树权限（父子联动） */
function handleCheckedTreeConnect(value, type) {
  menuCheckStrictly.value = value ? true : false;
}
const handleCheckChange = (node, selected) => {
  let list = selected.checkedKeys.concat(selected.halfCheckedKeys);
  emit("update:modelValue", list);
};
let setDefaultChecked = () => {
  nextTick(() => {
    if (menuOptions.value.length) {
      proxy.$refs.menuRef.setCheckedKeys(props.modelValue);
    }
  });
};

watch(
  () => [props.modelValue, menuOptions.value],
  (newValue, oldValue) => {
    if (newValue) setDefaultChecked();
  },
  { deep: true, immediate: true }
);
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
}
</style>
